﻿#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <assert.h>
#include <limits.h>

int my_atoi(const char* arr);

enum zhuangtai
{
	feifa,
	hefa
}moren = feifa;

int main()
{
	char arr[] = " -123a2";
	int ret = my_atoi(arr);
	if (moren == hefa)//合法
	{
		printf("合法返回：%d", ret);
	}
	else//非法
	{
		printf("不合法返回：%d\n", ret);
	}

	return 0;
}

int my_atoi(const char* arr)
{
	assert(arr);
	if (*arr == '\0')
	{
		return 0;
	}
	while (*arr == ' ')
	{
		arr++;
	}
	int flag = 1;
	if (*arr == '-')
	{
		flag = -1;
		arr++;
	}
	else if (*arr == '+')
	{
		flag = 1;
		arr++;
	}
	const char* cpy = arr;
	long long ret = 0;

	while (*arr >= '0' && *arr <= '9')
	{
		ret = ret * 10 + (*arr - '0') * flag;
		if (ret > INT_MAX || ret < INT_MIN)
		{
			return 0;
		}
		arr++;
	}
	if (*arr == '\0')
	{
		moren = hefa;
	}

	return (int)ret;
}